from lib.server.http import route
from lib.server.http.fs import net_fs
from utils import file


async def return_error(writer, path):
    response = (
        f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 17\r\n\r\n"
        + '{"value":"error"}'
    )
    writer.write(response)


async def return_ok(writer, path):
    response = (
        f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 14\r\n\r\n"
        + '{"value":"ok"}'
    )
    writer.write(response)


def create_headers(info):
    """生成HTTP Headers"""
    mime = info["mime"]
    size = info["size"]
    cache_age = 120  # 默认缓存120s

    header_str = ""

    head = f"HTTP/1.1 200 OK\r\n"

    common_headers = {
        "Content-Type": mime,
        "Content-Length": size,
    }

    etag = info["etag"]
    cache_headers = {
        "Cache-Control": f"max-age={cache_age}",
        "ETag": f"{etag}",
    }

    header_str += head

    for ch_key in common_headers:
        header_str += f"{ch_key}: {common_headers[ch_key]}" + "\r\n"

    for ch_key in cache_headers:
        header_str += f"{ch_key}: {cache_headers[ch_key]}" + "\r\n"

    return f"{header_str}\r\n"


async def visit_root(writer, path):
    # print(f"visit {path}")
    index_path = "/index.html"
    real_path = net_fs.real_path(index_path)
    if file.is_file(real_path):
        await visit_file(writer, index_path)
        return
    response = f"HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello world"
    writer.write(response)


async def visit_file(writer, path):
    (info, data) = net_fs.read(path)
    size = info["size"]

    if size <= 0 or data == None:
        return await return_error(writer, path)

    header = create_headers(info)
    # print(header)
    res = bytearray(bytes(header, "ascii"))

    # 超过设置大小
    if size > 0 and size > net_fs.get_max_file_size():
        writer.write(res)
        await net_fs.write_chunk(writer, path)
        return

    res.extend(data)
    writer.write(res)


async def visit_api(writer, path):
    await route.handle_routes(writer, path)
